package orm

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"xorm.io/core"
)

type Student struct {
	Id       int    `xorm:"INT(11) 'xxx'"`
	Username string `xorm:"VARCHAR(64) 'yyy'"`
	Address  string `xorm:"VARCHAR(256) 'zzz'"`
}

type Database struct {
	core *xorm.Engine
}

func NewORM() (x *Database) {
	x = &Database{}
	return
}

func (db *Database) Open(sqltype, addr string) error {

	var err error
	db.core, err = xorm.NewEngine(sqltype, addr)

	if err != nil {
		return err
	}

	db.core.SetMapper(core.SameMapper{}) //表示Struct的类的名称和数据库中相同
	//db.core.ShowSQL(true)                     //显示SQL语句
	//db.core.Logger().SetLevel(core.LOG_DEBUG) //打印SQL语句

	db.core.SetMaxIdleConns(128)
	db.core.SetMaxOpenConns(128)

	return err
}

type SelectFunc func(idx int, bean interface{}) error

func (db *Database) Select(obj interface{}, it SelectFunc) error {

	return db.core.Iterate(obj, func(idx int, bean interface{}) error {
		it(idx, bean)
		return nil
	})
}

func (db *Database) CreateTable(obj interface{}) error {

	return db.core.CreateTables(obj)
}

func (db *Database) DropTable(obj interface{}) error {

	return db.core.CreateTables(obj)
}

func (db *Database) TableIsExits(obj interface{}) bool {

	ok, _ := db.core.IsTableEmpty(obj)
	return ok
}

func (db *Database) Insert(obj interface{}) error {

	_, err := db.core.InsertOne(obj)
	return err
}

func (db *Database) Update(obj interface{}) error {

	_, err := db.core.Update(obj)
	return err
}

func (db *Database) Delete(obj interface{}) error {

	_, err := db.core.Delete(obj)

	return err
}

func (db *Database) SyncRecord(obj interface{}, cond interface{}) error {

	if err := db.Insert(obj); err != nil {
		if err := db.Update(obj); err != nil {
			return err
		} else {
			return nil
		}
	}
	return nil
}

func (db *Database) SyncTable(obj interface{}) error {

	return db.core.Sync2(obj)
}
func (db *Database) Close() {

	db.core.Close()
}
